<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/15 0015
 * Time: 16:58
 */

namespace App\App\Services;

use App\Models\Activity\ActivityService;
use App\Models\VoteCandidate\VoteCandidateService;
use App\Models\VoteGroup\VoteGroupService;

class DPService
{
    protected $voteCandidateService;
    protected $activity;
    protected $voteGroupService;

    public function __construct(VoteCandidateService $voteCandidateService, ActivityService $activity, VoteGroupService $voteGroupService)
    {
        $this->voteCandidateService = $voteCandidateService;
        $this->activity = $activity;
        $this->voteGroupService = $voteGroupService;
    }

    /**
     * 投票大屏
     *
     * @param $tplId
     */
    public function dpStatic($tplId)
    {
        $activityData = $this->activity->getActivityIdsByTpl($tplId);
        $path = public_path() . '/html';
        if ($activityData->count() > 0) {
            foreach ($activityData as $activity) {
                $this->dpStaticOne($activity->id, $path);
            }
        }
    }

    public function dpStaticOne($activityId, $path = null)
    {
        if (is_null($path)) {
            $path = public_path() . '/html';
        }

        $groupIds = $data = [];
        $groups = $this->voteGroupService->getItemByActivityId($activityId);
        if ($groups->count()<= 0) {
            return false;
        }
        foreach ($groups as $group) {
            array_push($groupIds, $group->id);
        }

        foreach ($groupIds as $k=>$groupId) {
            $group_info = $this->voteGroupService->getItemById($groupId);
            $items = $this->voteCandidateService->getItemsByConditions([['group_id',$groupId],['activity_id',$activityId]], 3);
            foreach ($items as $key=>$item) {
                $data[$k][$key]['group_name'] = $group_info['title'];
                $data[$k][$key]['title'] = $item['title'];
                $data[$k][$key]['voteNumber']=$item['votes_number'];
            }
        }
        $color=["#c2ef37","#efc237","#ef3b37"];

        $html = view('app.vote.unregister.index', ['vote_data' => $data, 'color'=>$color,'dataLen'=>count($data)])->__toString();
        if (!is_dir($path)) {
            mkdir($path);
        }
        file_put_contents($path . '/'.$activityId.'.html', $html);
    }
}
